// 数据接口定义
// 后台产品列表接口



// 以下接口为新接口
// 编辑、详情+"?id="
// 删除+"?del="
// 关闭+"t=0&del="
// 开启+"t=1&del="


// var API_BASE='https://www.mayizhihuan.com';
var API_BASE='https://qingzhi.quansuwangluo.com';
//权限组列表
var API_AUTH_GROUP=API_BASE+'/Supplier/Auth/group';
//权限列表
var API_AUTH=API_BASE+'/Supplier/Auth';
//管理员列表
var API_ADMIN=API_BASE+'/Supplier/admin';
// 当前登录用户信息
var API_ADMIN_INFO=API_BASE+'/Supplier/Index/info';
//修改当前用户密码
var API_SETPASSWORD=API_BASE+'/Supplier/Index/setPassword';


// 订单列表导出表格
var API_EXPORT_ORDER=API_BASE+'/Supplier/Export/order';
// 订单列表导出发货信息
var API_EXPORT_ORDERGOODS=API_BASE+'/Supplier/Export/ordergoods';
// 订单退款(order-list3作废)
var API_ORDER_REFUND=API_BASE+'/Supplier/order/refund';
// 订单商品退款退券
var API_ORDERGOODS_REFUND=API_BASE+'/Supplier/GoodsRefund';
// 订单退款详情
var API_ORDER_REFUNDDETAIL=API_BASE+'/Supplier/pay';
// 訂單物流列表
var API_ORDER_TRANSPORT=API_BASE+'/Supplier/OrderExpress';
// 商城发货
var API_GOODSSEND=API_BASE+'/Supplier/Delivery';
// 商品管理
var API_GOODS=API_BASE+'/Supplier/Goods';
// 商品分类
var API_GOODSCLASS=API_BASE+'/Supplier/Class/goods';
// 回复评论
var API_BACKEVALUATE=API_BASE+'/Supplier/Evaluate/reply_evaluate';
// 单独退款
var API_REFUND_MONEY='/Supplier/pay';

// 意见反馈
var API_FEEDBACK=API_BASE+'/Supplier/Feedback';
// 订单管理
var API_ORDERLIST=API_BASE+'/Supplier/Order/goods';
// 订单评论列表
var API_ORDEREVALUATE=API_BASE+'/Supplier/Evaluate';
// 后台统计
var API_SYSTEM_TONGJI=API_BASE+'/Supplier/CountAll';
// 清除缓存
var API_CLEARCOOKIES=API_BASE+'/Supplier/Runtime/clear';
// oss后台直传
var API_OSSUPLOAD=API_BASE+'/Supplier/upload/getSignedUrl';
// 快递查询
var API_EXPRESS=API_BASE+'/express';
// 运费模板
var API_TRANSTMP=API_BASE+'/Supplier/Transport';
// 运费模板详情
var API_TRANSTMPDETAIL=API_BASE+'/Supplier/Transport/extend';

//上传图片
var API_IMGUPLOAD=API_BASE+'/Supplier/Upload/image';
// 文件上传
var API_FILEUPLOAD=API_BASE+'/Supplier/Upload/file';
// 系统信息统计
var API_SYSTEM_INFO=API_BASE+'/Supplier/Index';

var API_VALIDATE=API_BASE+'/Supplier/Index/verify';

// 全局变量
var url_login='/UserManage/login.html';



var shippinglist=[
    {code:"SF",name:"顺丰快递"},
    {code:"YD",name:"韵达快递"},
    {code:"STO",name:"申通快递"},
    {code:"ZTO",name:"中通速递"},
    {code:"HHTT",name:"天天快递"},
    {code:"HTKY",name:"百世快递"},
    {code:"BTWL",name:"百世快运"},
    {code:"EMS",name:"EMS"},
    {code:"AJ",name:"安捷快递"},
    {code:"ANE",name:"安能物流"},
    {code:"AXD",name:"安信达快递"},
    {code:"BQXHM",name:"北青小红帽"},
    {code:"BFDF",name:"百福东方"},
    {code:"CCES",name:"CCES快递"},
    {code:"CITY100",name:"城市100"},
    {code:"COE",name:"COE东方快递"},
    {code:"CSCY",name:"长沙创一"},
    {code:"CDSTKY",name:"成都善途速运"},
    {code:"DBL",name:"德邦"},
    {code:"DSWL",name:"D速物流"},
    {code:"DTWL",name:"大田物流"},
    {code:"FAST",name:"快捷速递"},
    {code:"FEDEX",name:"FEDEX联邦(国内件)"},
    {code:"FEDEX_GJ",name:"FEDEX联邦(国际件)"},
    {code:"FKD",name:"飞康达"},
    {code:"GDEMS",name:"广东邮政"},
    {code:"GSD",name:"共速达"},
    {code:"GTO",name:"国通快递"},
    {code:"GTSD",name:"高铁速递"},
    {code:"HFWL",name:"汇丰物流"},
    {code:"HLWL",name:"恒路物流"},
    {code:"HOAU",name:"天地华宇"},
    {code:"hq568",name:"华强物流"},
    {code:"HXLWL",name:"华夏龙物流"},
    {code:"HYLSD",name:"好来运快递"},
    {code:"JGSD",name:"京广速递"},
    {code:"JIUYE",name:"九曳供应链"},
    {code:"JJKY",name:"佳吉快运"},
    {code:"JLDT",name:"嘉里物流"},
    {code:"JTKD",name:"捷特快递"},
    {code:"JXD",name:"急先达"},
    {code:"JYKD",name:"晋越快递"},
    {code:"JYM",name:"加运美"},
    {code:"JYWL",name:"佳怡物流"},
    {code:"KYWL",name:"跨越物流"},
    {code:"LB",name:"龙邦快递"},
    {code:"LHT",name:"联昊通速递"},
    {code:"MHKD",name:"民航快递"},
    {code:"MLWL",name:"明亮物流"},
    {code:"NEDA",name:"能达速递"},
    {code:"PADTF",name:"平安达腾飞快递"},
    {code:"QCKD",name:"全晨快递"},
    {code:"QFKD",name:"全峰快递"},
    {code:"QRT",name:"全日通快递"},
    {code:"RFD",name:"如风达"},
    {code:"SAD",name:"赛澳递"},
    {code:"SAWL",name:"圣安物流"},
    {code:"SBWL",name:"盛邦物流"},
    {code:"SDWL",name:"上大物流"},
    {code:"SFWL",name:"盛丰物流"},
    {code:"SHWL",name:"盛辉物流"},
    {code:"ST",name:"速通物流"},
    {code:"STWL",name:"速腾快递"},
    {code:"SURE",name:"速尔快递"},
    {code:"TSSTO",name:"唐山申通"},
    {code:"UAPEX",name:"全一快递"},
    {code:"UC",name:"优速快递"},
    {code:"WJWL",name:"万家物流"},
    {code:"WXWL",name:"万象物流"},
    {code:"XBWL",name:"新邦物流"},
    {code:"XFEX",name:"信丰快递"},
    {code:"XYT",name:"希优特"},
    {code:"XJ",name:"新杰物流"},
    {code:"YADEX",name:"源安达快递"},
    {code:"YCWL",name:"远成物流"},
    {code:"YDH",name:"义达国际物流"},
    {code:"YFEX",name:"越丰物流"},
    {code:"YFHEX",name:"原飞航物流"},
    {code:"YFSD",name:"亚风快递"},
    {code:"YTKD",name:"运通快递"},
    {code:"YTO",name:"圆通速递"},
    {code:"YXKD",name:"亿翔快递"},
    {code:"YZPY",name:"邮政平邮/小包"},
    {code:"ZENY",name:"增益快递"},
    {code:"ZHQKD",name:"汇强快递"},
    {code:"ZJS",name:"宅急送"},
    {code:"ZTE",name:"众通快递"},
    {code:"ZTKY",name:"中铁快运"},
    {code:"ZTWL",name:"中铁物流"},
    {code:"ZYWL",name:"中邮物流"},
    {code:"AMAZON",name:"亚马逊物流"},
    {code:"SUBIDA",name:"速必达物流"},
    {code:"RFEX",name:"瑞丰速递"},
    {code:"QUICK",name:"快客快递"},
    {code:"CJKD",name:"城际快递"},
    {code:"CNPEX",name:"CNPEX中邮快递"},
    {code:"HOTSCM",name:"鸿桥供应链"},
    {code:"HPTEX",name:"海派通物流公司"},
    {code:"AYCA",name:"澳邮专线"},
    {code:"PANEX",name:"泛捷快递"},
    {code:"PCA",name:"PCA"}, 
    {code:"UEQ",name:"UEQ"}, 

]

// 文字滚动效果 
function countUp(elem, endVal, startVal, duration, decimal) {
    //传入参数依次为 数字要变化的元素，最终显示数字，数字变化开始值，变化持续时间，小数点位数
    // 调用实例countUp(document.getElementById("twitternum"), 100, 1, 500, 0);
    var startTime = 0;
    var dec = Math.pow(10, decimal);
    var progress,value;
    function startCount(timestamp) {
        startTime = !startTime ? timestamp : startTime;
        progress = timestamp - startTime;
        value = startVal + (endVal - startVal) * (progress / duration);
        value = (value > endVal) ? endVal : value;
        value = Math.floor(value*dec) / dec;
        elem.innerHTML = value.toFixed(decimal);
        progress < duration && requestAnimationFrame(startCount)
    }
    requestAnimationFrame(startCount)
}


// 单图上传移除选中图片
$(document).on('click','i.fun-img-del',function(){
    var idname=$(this).data("id");
    var inputname=$(this).data("inputname");
    $(idname).empty().html('<input type="hidden" name="'+inputname+'" value="">');
})


// 多图上传时移除选中的图片
function fj_close(obj){
    $(obj).parents("li").remove();
}

// 限制多图上传最多只能上传9张
function openuploadimages(){

    var len=$("#fujian li").length;
    if(len<9){
        _open('添加附件','article-imageupload.html?type=image&idname=fujian&api=article&single=0&inputname=images','750px','470px',true)
    }else{
        layer.msg('最多只能上传9张图', {icon:5,time:2000});
    }

}

// 图片弹出层预览
var layerindex=0;
var layerurls=[];
$(document).on('click','span.fun-openlayer',function(){

    layerindex=$(this).data("index");
    layerurls=[];

    $(this).closest("td").find(".fun-openlayer").each(function(){
        layerurls.push($(this).data("url"))         
    })

    var url=layerurls[layerindex];
    
    $("body").append('<div id="layerimg"><img src="'+url+'"><i class="Hui-iconfont menu_dropdown-arrow left">&#xe67d;</i><i class="Hui-iconfont menu_dropdown-arrow right">&#xe63d;</i></div>');
    layer.open({
      type: 1,
      title: false,
      closeBtn: 0,
      area: '516px',
      skin: 'layui-layer-nobg', //没有背景色
      shadeClose: true,
      content: $('#layerimg'),
      end:function(){
            $("#layerimg").remove();
      },
    });
})
// 右翻
$(document).on('click','#layerimg i.right',function(){

    if(layerindex==layerurls.length-1){
        layer.msg('已是最后一张', {icon:5,time:1000});
        return;
    }
    layerindex=parseInt(layerindex)+1;
    $("#layerimg img").attr("src",layerurls[layerindex]);
})
// 左翻
$(document).on('click','#layerimg i.left',function(){
    if(layerindex==0){
        layer.msg('已是第一张', {icon:5,time:1000});
        return;
    }
    layerindex=parseInt(layerindex)-1;
    $("#layerimg img").attr("src",layerurls[layerindex]);
})
// 图片弹出层预览结束

//获取当前时间，格式YYYY-MM-DD
function getNowFormatDate() {
    var date = new Date();
    var seperator1 = "-";
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = year + seperator1 + month + seperator1 + strDate;
    return currentdate;
}

// 调用富文本编辑器
function getueidt(){
    var ue = UE.getEditor('editor', {
        initialFrameHeight: 300,
        imageCompressEnable: false,
        // initialFrameWidth:100
        
    });
    UE.registerUI('button', function(editor, uiName) {
        //注册按钮执行时的command命令，使用命令默认就会带有回退操作
        editor.registerCommand(uiName, {
            execCommand: function() {
                // alert('execCommand:' + uiName)
                _open('上传图片','article-imageupload.html?type=ueditor&idname=uedit&api=ueditor&single=0&inputname=uedit','710px','470px',true)
            }
        });
        //创建一个button
        var btn = new UE.ui.Button({
            //按钮的名字
            name: "上传图片",
            //提示
            title: "上传图片",
            //添加额外样式，指定icon图标，这里默认使用一个重复的icon
            cssRules: 'background-position: -726px -77px;',

            //点击时执行的命令
            onclick: function() {
                //这里可以不用执行命令,做你自己的操作也可
                editor.execCommand(uiName);
            }
        });
        //当点到编辑内容上时，按钮要做的状态反射
        editor.addListener('selectionchange', function() {
            var state = editor.queryCommandState(uiName);
            if (state == -1) {
                btn.setDisabled(true);
                btn.setChecked(false);
            } else {
                btn.setDisabled(false);
                btn.setChecked(state);
            }
        });
        //因为你是添加button,所以需要返回这个button
        return btn;
    }, [38]);
}



// 获取0-9，A-Z随机文件名
var chars = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
function getrandom(an) {
    // an为个数
    var res = "";
    var index=an || 1;
    for(var ia = 0; ia < index ; ia ++) {
    var id = Math.ceil(Math.random()*35);
    res += chars[id];
    }
    return res;
}
function getrandom2(num){
    // 生成十位字母加数字随机数
    // var arr = [];
    // var tt=num || 1;
    // for (var i=0;i<tt;i++) {
    //     var n = Math.random().toString().substr(2,10);
    //     arr.push(n);
    // }        
    // // 去重
    // var ukeys = [];
    //     for (var i = 0; i < arr.length; i++) {
    //         if (ukeys.indexOf(arr[i]) == -1) {
    //             ukeys.push(arr[i]);
    //         }
    //     }
    //     // 数组处理，便于在Html文档中显示
    // var keys = '';
    // for (var i=0;i<ukeys.length;i++) {
    //     // ukeys[i] += '<br>'
    //     keys += ukeys[i]
    // }
    // 获取当前时间戳
    var time=parseInt((new Date()).valueOf()+Math.random().toString().substr(2,3)).toString(16);

    return time;

}




// 获取网址中包含的参数
function getUrlParam(name)
{
// var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
// var r = window.location.search.substr(1).match(reg);  //匹配目标参数
// if (r!=null) return unescape(r[2]); return null; //返回参数值

var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
var url = window.location.search.substr(1);
url = decodeURI(url); 
var r = url.match(reg);  //匹配目标参数
if (r!=null) return unescape(r[2]); return null; //返回参数值
} 

// 设置cookie
function setCookie(objName, objValue, objmin){//添加cookie单位分钟 
    var str = objName + "=" + escape(objValue); 
    if (objmin > 0) {//为0时不设定过期时间，浏览器关闭时cookie自动消失 
        var date = new Date(); 
        var ms = objmin * 60 * 1000; 
        date.setTime(date.getTime() + ms); 
        str += "; expires=" + date.toGMTString(); 
    } 
    document.cookie = str; 
      // alert("添加cookie成功"); 
} 

// 读取cookie
function getCookie(objName){//获取指定名称的cookie的值 
    var arrStr = document.cookie.split("; "); 
    for (var i = 0; i < arrStr.length; i++) { 
        var temp = arrStr[i].split("="); 
        if (temp[0] == objName) 
        return unescape(temp[1]); 
    } 
} 

// 搜索列表中的内容值
$(document).on('click','td.fun-search',function(){
    var name=$(this).data("name");
    var value=$(this).data("value");
    
    var showname=$(this).data("show") || $(this).html();
    var url=API+"?"+name+"="+value;
    
    $('input[name='+name+']').val(value);
    $('select[name='+name+']').append("<option value='"+value+"' selected>"+showname+"</option>");

    loaddata(url,1,true);
})

// 打开层（title信息，网址，宽，高，是否可全屏）
function _open(title,url,w,h,full){ 
    var index = layer.open({
        type: 2,
        title: title,
        content: url,
        area:[w,h],
        maxmin: full,   
        shadeClose: true,
    });
    // layer.full(index);
}



/*推荐取消推荐*/
$(document).on('click','input.fun-tj',function(){
    var id=$(this).parent().parent().find("td.valueid:first-child input").val();
    var state=this.checked;
    state=state?'1':'0';
    var that=$(this);
    var url=API+"?id="+id;
    $.post(url,
    {
      is_index:state,
    },
    function(data){
        if(data.status==1){
                layer.msg("操作成功",{icon:1,time:1000});   
            }
    }); 
})

/*推荐取消合作*/
$(document).on('click','input.fun-hz',function(){
    var id=$(this).parent().parent().find("td.valueid:first-child input").val();
    var state=this.checked;
    state=state?'1':'0';
    var that=$(this);
    var url=API+"?id="+id;
    $.post(url,
    {
      is_friend:state,
    },
    function(data){
        if(data.status==1){
                layer.msg("操作成功",{icon:1,time:1000});   
            }
    }); 
})



// 判断登录
function checkStatus(data){
    if(data.status==0){
        layer.msg(data.info, {icon:2,time:1000});
        if(data.info=="请先登录"){
        //     setTimeout(function(){
        //         window.parent.location.href=url_login;

        // }, 3000)
             window.parent.location.href=url_login;
        } 
        return false;
    }
    return true;
}





//调用数据并分页
var p;//当前页码


function loaddata(api,curr,lazyflag,pageflag){ 

    lazyflag=lazyflag || true;
    pageflag=pageflag || true;
    curr=curr || location.hash.replace('#!fenye=', '') || 1;
    var start=true;

    $.getJSON(api, {p: curr}, function(data){      
        if(!checkStatus(data)) return;    
        if(data.datas=='' || data.datas.length==0){
            document.getElementById('content_sp').innerHTML='<tr class="text-c"><td colspan="20">暂无数据</td></tr>';
            $("#dataall").html('共有数据：<strong>'+data.total+'</strong> 条');//总数据量
            $("#page").html("");
        }else{
            console.log("tt")
            var pages=Math.ceil(data.total/data.count);
            if(typeof(data.total)!= "undefined" && data.total!=""){
                $("#dataall").html('共有数据：<strong>'+data.total+'</strong> 条');//总数据量
            }
            $("#remark").html(data.url);
            var data={'list':data.datas};
            var html=template('test',data);


            
            
            $("#content_sp").parent().parent().hide();
            $("#content_sp").parent().parent().next().hide();
            $("content_sp").empty();
            $("#content_sp").html(html);
            $("#content_sp").parent().parent().slideDown(300);
            $("#content_sp").parent().parent().next().slideDown(300,function(){
                if(lazyflag){
                    // 懒加载图片
                    lazy.init();
                }
            });

            //显示分页
            laypage({
                cont : 'page', //容器例如：<div id="page1"></div>
                pages: pages, //通过后台拿到的总页数
                curr: curr,
                skip: true,
                hash: 'fenye', //自定义hash值
                jump : function(obj, first){ //触发分页后的回调
                    if(!first){ //点击跳页触发函数自身，并传递当前页：obj.curr
                        loaddata(api,obj.curr,lazyflag); 
                    }
                }
            });

            


            //键盘操作，左键上一页，右键下一页
            $(document).on('keydown',function(event){
                
                var newpage;

                if(start){
                    // console.log('keydown');
                    if(event.keyCode=='37'){
                        newpage=parseInt(curr)-1; 
                        // console.log(newpage+":37");
                        if(parseInt(curr)==1){  
                            layer.msg("已是第一页",{icon:2,time:1000});
                            return;
                        }else{
                            if(typeof(kk)!=="undefined"){
                                loaddata(kk,newpage,true);
                            }else{
                                loaddata(API,newpage,true);
                            }
                            start=false;
                        } 
                         
                    }else if(event.keyCode=='39'){
                        newpage=parseInt(curr)+1;  
                        // console.log(newpage+":39");
                        if(parseInt(curr)==pages){
                            layer.msg("已是最后一页",{icon:2,time:1000});
                            return;
                        }else{
                            if(typeof(kk)!=="undefined"){
                                loaddata(kk,newpage,true);
                            }else{
                                loaddata(API,newpage,true);
                            } 
                            start=false;
                        }
                        
                    }
                     
                }
                   
            })
        } 
    }); 
};


//szc获取URL中的参数,兼容Thinkphp
function getQueryString(id){
    var temp = location.search.toLowerCase().split(id+"=")[1] || "";
    temp=temp.indexOf("&")>=0 ? temp.split("&")[0] : temp; 
    if(temp==''){
        var sep='/';
        var start=location.pathname.toLowerCase().indexOf(sep+id+sep);
        start+=id.length+sep.length;
        temp=location.pathname.toLowerCase().substring(start+1);
        temp=temp.match(/\w*[\.\/\?]/);
        temp=temp.toString().substr(0,temp.toString().length-1);
    }
    return temp;
}
//SZC
//input.fun-start-stop显示关闭按钮
$(document).on('click','input.fun-start-stop',function(e){
    var state=this.checked;
    state=state?'1':'0';
    var id=$(this).parent().parent().find("td.valueid:first-child input:checkbox").val();
    $.getJSON(API,{t:state,del:id},function(data){
        checkStatus(data);
        if(data.status==1){
            layer.msg(data.info,{icon:1,time:1000});
        }else{
            layer.msg(data.info,{icon:2,time:1000});

            if(state=='0'){
                $(this).prop("checked",true);
            }else{
                $(this).prop("checked",false);
            } 
        }        
    })
})

// 编辑部分内容
// 标准格式<td class="fun-edit" data-classname="类名"><input type="text" name="" value=""></td>
var fun_value0='';
$(document).on('focus','td.fun-edit input',function(){  
    fun_value0=$(this).val();
})
$(document).on('blur','td.fun-edit input',function(){
        
    var value=$(this).val();
    var classname=$(this).closest("td.fun-edit").data("classname");
    var changefee=$(this).closest("td.fun-edit").find("span");
    var that=$(this);

    var parent=$(this).closest("td.fun-edit");
    var oid=$(this).closest("tr").find("td.valueid input:checkbox").val();
    var param='{type:"edit",oid:'+oid+','+classname+':"'+value+'"}';

    param=eval("("+param+")"); 
    var text="是否确定修改?";
    console.log(value)
    if(classname=="total_transport"){
        text=text+"<br>修改运费会改变订单编号请知晓"
    }
    if(fun_value0!==value){
        layer.confirm(text,function(index){
            layer.load();
            $.post(API,param,function(data){
                if(!checkStatus(data)) return;
                changefee.text(data.url)
                layer.closeAll('loading');
                layer.close(index);
            },'json')
        },function(){
            that.val(fun_value0)
        })
        
    }
})

//input.fun-index-show显示关闭按钮
$(document).on('click','input.fun-index-show',function(e){
    var state=this.checked;
    state=state?'1':'0';
    var id=$(this).parent().parent().find("td.valueid:first-child input:checkbox").val();
    $.getJSON(API,{index:state,del:id},function(data){
        checkStatus(data);
        if(data.status==1){
            layer.msg(data.info,{icon:1,time:1000});
        }else{
            layer.msg(data.info,{icon:2,time:1000});

            if(state=='0'){
                $(this).prop("checked",true);
            }else{
                $(this).prop("checked",false);
            } 
        }        
    })
})



//a.fun-all批量操作，start开启，stop关闭，del删除
$(document).on('click','a.fun-all',function(e){
    var type=$(this).data("type");
    var delallurl=API;
    var isshow;
    if(type=="del"){
        delallurl=delallurl+"?del=";
    }else if(type=="stop"){
        delallurl=delallurl+"?t=0&del=";
        isshow=false;
    }else if(type=="indexshow"){
        delallurl=delallurl+"?index=1&del=";
        isshow=true;
    }else if (type=="indexhide") {
        delallurl=delallurl+"?index=0&del=";
        isshow=false;
    }else{
        delallurl=delallurl+"?t=1&del=";
        isshow=true;
    }
    if($("#content_sp .valueid input[type='checkbox']:checked").length<1){
        layer.msg('请选择要操作的内容!',{icon:2,time:2000});
    }else{
        var ids="";
        $("#content_sp .valueid input[type='checkbox']:checked").each(function(e){
            ids=ids+$(this).val()+",";
        })
        delallurl=delallurl+ids;
        if(type=="del"){
            if(confirm("确认要删除？")){

                $.getJSON(delallurl,function(data){
                    checkStatus(data);
                    if(data.status==1){
                        $("#content_sp .valueid input[type='checkbox']:checked").parent().parent().remove();
                        window.parent.layer.msg(data.info,{icon:1,time:2000});
                        $("table .valueid input[type='checkbox']:checked").prop("checked",false);
                    }
                })                
            }
        }else if(type=="indexshow" || type=="indexhide"){
            $.getJSON(delallurl,function(data){
                checkStatus(data);
                if(data.status==1){
                    $("#content_sp .valueid input[type='checkbox']:checked").parent().parent().parent().find("td.valueid input[type='checkbox']:checked").parent().parent().find("td.td-indexshow input[type='checkbox']").prop("checked",isshow);
                    window.parent.layer.msg(data.info,{icon:1,time:2000});
                    $("table .valueid input[type='checkbox']:checked").prop("checked",false);
                }
            })
        }else{
            $.getJSON(delallurl,function(data){
                checkStatus(data);
                if(data.status==1){
                    $("#content_sp .valueid input[type='checkbox']:checked").parent().parent().parent().find("td.valueid input[type='checkbox']:checked").parent().parent().find("td.td-status input[type='checkbox']").prop("checked",isshow);
                    window.parent.layer.msg(data.info,{icon:1,time:2000});
                    $("table .valueid input[type='checkbox']:checked").prop("checked",false);
                }
            })
        }

        
        
    }   
})

//.fun-del单个删除
$(document).on('click','a.fun-del',function(e){
    var that=$(this); 
    if(confirm("确认要删除？")){ 
        var id=$(this).closest("tr").find("td.valueid input:checkbox").val();
        var delurl=API+'?del='+id; 
        $.getJSON(delurl,function(data){
            checkStatus(data);
            if(data.status==1){
                that.parents("tr").remove();
                window.parent.layer.msg(data.info,{icon:1,time:2000});
            }
        });
    } 
})

//.fun-paixu排序input
$(document).on('blur','input.fun-paixu',function(e){
    var nowk=$(this).val();
    var oldk=$(this).attr("value");
    var id=$(this).closest("tr").find("td.valueid input:checkbox").val();
    var inputname=$(this).attr("name");
    

    if (nowk!=oldk){
        var paixuurl=API+"?id="+id;
        var p=$(this).val();
        
        var strs={};
        strs[inputname]=p;
        
        $.post(paixuurl,
            strs,
            // {
            //   menu_sort:p,
            // },
            function(data){
                checkStatus(data);
                if(data.status==1){
                    loaddata(API,1,true);
                }
            }
        ); 
    }
})


//全选按钮
$(".sort0 .valueid input:checkbox").on("click" , function(){
    $(this).closest("table").find(".valueid input:checkbox").prop("checked",$(this).prop("checked"));
});

// 一级分类点击事件
$(document).on('click','.sort1 .valueid input:checkbox',function(){
    // 展开子分类
    $(this).parent().parent().nextUntil('.sort1').find('.valueid input:checkbox').prop("checked",$(this).prop("checked"));
    var checklen1=$(".sort1 .valueid input:checkbox:checked").length;
    var len1=$(".sort1").length;
    $(".sort0 input:checkbox").prop("checked",checklen1==len1);//全选按钮
})

// 二级分类点击事件
$(document).on('click','.sort2 .valueid input:checkbox',function(){
    $(this).closest(".sort2").nextUntil('.sort2').filter(".sort3").find('.valueid input:checkbox').prop("checked",$(this).prop("checked"));
    
    var checklen2=$(this).closest(".sort2").prevAll(".sort1").first().nextUntil('.sort1').filter(".sort2").find(".valueid input:checkbox:checked").length;
    var len2=$(this).closest(".sort2").prevAll(".sort1").first().nextUntil('.sort1').filter(".sort2").find(".valueid input:checkbox").length;  
    $(this).closest(".sort2").prevAll(".sort1").first().find(".valueid input:checkbox").prop("checked",checklen2==len2);

    var checklen1=$(".sort1 .valueid input:checkbox:checked").length;
    var len1=$(".sort1").length;
    $(".sort0 input:checkbox").prop("checked",checklen1==len1);//全选按钮
})

// 三级分类点击事件
$(document).on('click','.sort3 .valueid input:checkbox',function(){
    //点击三级目录全选旗下司机目录
    $(this).closest(".sort3").nextUntil('.sort3').filter(".sort4").find('.valueid input:checkbox').prop("checked",$(this).prop("checked"));
    
    //点击三级目录取消其上二级目录的权限
    var checklen3=$(this).closest(".sort3").prevAll(".sort2").first().nextUntil('.sort2').filter(".sort3").find(".valueid input:checkbox:checked").length;
    var len3=$(this).closest(".sort3").prevAll(".sort2").first().nextUntil('.sort2').filter(".sort3").find(".valueid input:checkbox").length;
    $(this).closest(".sort3").prevAll(".sort2").first().find(".valueid input:checkbox").prop("checked",checklen3==len3);
    
    //点击三级目录影响了二级目录全选从而改变一级目录全选
    var checklen4=$(this).closest(".sort3").prevAll(".sort1").first().nextUntil('.sort1').filter(".sort2").find(".valueid input:checkbox:checked").length;
    var len4=$(this).closest(".sort3").prevAll(".sort1").first().nextUntil('.sort1').filter(".sort2").find(".valueid input:checkbox").length;
    $(this).closest(".sort3").prevAll(".sort1").first().find(".valueid input:checkbox").prop("checked",checklen4==len4);

    //全选按钮
    var checklen1=$(".sort1 .valueid input:checkbox:checked").length;
    var len1=$(".sort1").length;
    $(".sort0 input:checkbox").prop("checked",checklen1==len1);
})

// a.fun-openclose显示隐藏子分类
$(document).on('click','a.fun-openclose',function(){
    var flag=$(this).data("flag");
    var sortnum=$(this).data("sortnum");
    var sortnext=sortnum+1;
    
    if(flag=='0'){
        $(this).closest(".sort"+sortnum).nextUntil(".sort"+sortnum).filter(".sort"+sortnext).slideDown(10);
        $(this).data("flag","1");
        $(this).find("span").text("-");
        // console.log(flag);
        // $(this).closest(".sort"+sortnum).nextUntil(".sort"+sortnum).filter(".sort"+sortnext).css('background-color','red');
        
    }else{
        $(this).closest(".sort"+sortnum).nextUntil(".sort"+sortnum).filter(".sort"+sortnext).slideUp(10);
        $(this).data("flag","0");
        $(this).find("span").text("+");
    }  
})


// 获取当前时间年-月-日 时:分:秒
function getNowTime(){
    var date = new Date();
    var year = date.getFullYear();
    var month = ((date.getMonth()+1)<10)?'0'+(date.getMonth()+1):(date.getMonth()+1);
    
    var day = (date.getDate()<10)?'0'+date.getDate():date.getDate();
    
    var hour = (date.getHours()<10)?'0'+date.getHours():date.getHours();
    var minute = (date.getMinutes()<10)?'0'+date.getMinutes():date.getMinutes();
    var second = (date.getSeconds()<10)?'0'+date.getSeconds():date.getSeconds();
    var time=year+'-'+month+'-'+day+' '+hour+':'+minute+':'+second;
    return time;
}

// 当前时间+yue月
function getNowTime2(yue){
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth()+1;
    if(month==12){
        month = 1;
        year = year+1;
    }else{
        month = month +1;
    }

    month = (month<10)?'0'+month:month;
    
    var day = (date.getDate()<10)?'0'+date.getDate():date.getDate();
    
    var hour = (date.getHours()<10)?'0'+date.getHours():date.getHours();
    var minute = (date.getMinutes()<10)?'0'+date.getMinutes():date.getMinutes();
    var second = (date.getSeconds()<10)?'0'+date.getSeconds():date.getSeconds();
    var time=year+'-'+month+'-'+day+' '+hour+':'+minute+':'+second;
    return time;
}


// 根据图片地址获取图片类型图标
function getIcon(string){
    var icon;
    var image=string;
    if(string.indexOf(".")>0){
        string=string.substr(string.lastIndexOf(".")+1).toLowerCase();
    }

    if(string=="txt"){
        icon="/Manage/images/txt.png";
    }else if(string=="xlsx" || string=="xls"){
        icon="/Manage/images/excel.png";
    }else if(string=="zip" || string=="rar"){
        icon="/Manage/images/rar.png";
    }else if(string=="doc" || string=="docx"){
        icon="/Manage/images/word.png";
    }else if(string=="psd"){
        icon="/Manage/images/ps.png";
    }else if(string=="html" || string=="htm"){
        icon="/Manage/images/ie.png";
    }else if(string=="ppt" || string=="pptx"){
        icon="/Manage/images/ppt.png";
    }else if(string=="pdf"){
        icon="/Manage/images/pdf.png";
    }else if(string=="txt"){
        icon="/Manage/images/txt.png";
    }else if(string=='apk'){
        icon="/Manage/images/apk.png";
    }else if(string=='mp3'){
        icon="/Manage/images/audio.png";
    }else if(string=='mp4'){
        icon="/Manage/images/video.png";
    }else{
        icon=image;
    }

    return icon;
}

// 顶部搜索栏，输入关键词后，回车搜索事件
$("nav").keypress(function(e) {  
   if(e.which == 13) {  
        $("#search").click();  
   }  
}); 
// 分页栏，输入页码后，回车搜索事件
$("#page").keypress(function(e) {  
   if(e.which == 13) {  
        $("button.laypage_btn").click();  
   }  
});



// Validform表单验证提交函数
// function Validformsubmit(form){
//     $(form).Validform({
//         tiptype:2,
//         ajaxPost:true,
//         callback:function(data){
//             if(!checkStatus(data)) return;
//             if(data.status=='1'){
//                 var index = parent.layer.getFrameIndex(window.name);
//                 parent.parent.layer.msg("操作成功", {icon:1,time:1000});
//                 parent.$('.btn-refresh').click();
//                 window.parent.location.reload();
//                 parent.layer.close(index);      
//             }
//         }
//     });
// }

function Validformsubmit(form){
    $(form).Validform({
        tiptype:2,
        ajaxPost:true,
        callback:function(data){
            if(!checkStatus(data)) return;
            if(data.status=='1'){
                var index = parent.layer.getFrameIndex(window.name);
                parent.parent.layer.msg(data.info, {icon:1,time:1000});
                // window.parent.location.reload();
                window.parent.loaddata(parent.kk);
                parent.layer.close(index); 
                // console.log("kk:"+window.parent.kk)     
            }
        }
    });
}
/**
 * 文件大小单位格式化
 * @param bytes 文件实际大小，单位byte
 * @param prec 转换后精确度，默认精确到小数点后两位
 * @return 转换后的大小+单位的字符串
 */
function fsize(bytes,prec){
    prec=prec || 2;
    var rank=0;
    var size=bytes;
    var unit="B";
    while(size>1024){
        size=size/1024;
        rank++;
    }
    size=Math.round(size,prec);
    switch (rank){
        case "1":
            unit="KB";
            break;
        case "2":
            unit="MB";
            break;
        case "3":
            unit="GB";
            break;
        case "4":
            unit="TB";
            break;
        default :
            
    }
    return size+" "+unit;
}

// 验证函数
function testing(e, t) {
    var flag;
    var rule;
    if (e == undefined) {
        showtips("参数缺失")
        return;
    }

    if (t == "mobile") {
        // 手机号码
        rule = /^1[34578]\d{9}$/
    } else if (t == 'username') {
        rule = /^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$/;
    } else if (t == 'price') {
        // 价格：正浮点数 
        rule = /^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$/;
    } else if (t == 'password') {
        // 密码4-20字符
        rule = /^.{4,20}$/;
    } else if (t == 'num') {
        // 数量
        rule = /^([1-9][0-9]*)$/;
    } else {
        // 非空验证1-50字符
        rule = /^.{1,50}$/;
    }

    rule.test(e) ? flag = true : flag = false;
    return flag;
}


$(document).ready(function(){ 
    　$.ajaxSetup({
    　　　 timeout: 60000,
    　　　 dataType: 'html',
    　　　 //请求成功后触发
    　　　 success: function (data) { 
           // console.log('success'); 
            },
　　　 //请求失败遇到异常触发
　　　 error: function (xhr, status, e) { 
           // console.log(xhr);

           layer.msg('数据加载失败', {icon:5,time:3000});
       },
　　　　//完成请求后触发。即在success或error触发后触发
　　　 complete: function (xhr, status) { 
           layer.closeAll('loading');
           // console.log("complete")

       },
　　　 //发送请求前触发
　　　 beforeSend: function (xhr) {
    　　　　//可以设置自定义标头
    　　     layer.load();
    // console.log("begin")
            //可以设置自定义标头
    // 　　　　xhr.setRequestHeader('withCredentials', true);
    // console.log(xhr);　　

　　　 },

　　})

    // 右上角刷新功能
    $(document).on('click','a.reload',function(e){
        // loaddata(API);
        location.reload();
    })

    // 日期选择input添加删除按钮
    $(document).on('focus','input',function(){
        $(this).next('i').show(500);
        
        // 清空时间
        $(document).on('click','i#inputclear',function(){
            $(this).prev("input").val("");
        })
    })

    //屏幕F5刷新子框架而不是总页面
    $(document).on('keydown',function(event){
        if(event.keyCode=='116'){   
            event.preventDefault();
            window.location.href=window.location.href;
        }            
    })

    
    // 根据字段升降排序
    // data-name为排序的关键字字段名，data-flag为升序还是降序排序
    $("th.fun-sort").append('<i class="Hui-iconfont zhuan90">&#xe6ee;</i>');//添加样式
    $(document).on('click','th.fun-sort',function(){
        console.log(kk)
        if(kk.indexOf('?') >= 0){
            kk=kk+"&";
        }else{
            kk=API+"?";
        }
        
        
        var sortname=$(this).data("name");
        var flag=$(this).data("flag");
        kk=kk+'order='+sortname+'&desc='+flag;
        loaddata(kk,1,true);
        $('th.fun-sort').removeClass('fun-sort-active');
        $('th.fun-sort').find('i').html('&#xe6ee;').addClass('zhuan90');
        $(this).find('i').removeClass('zhuan90');
        $(this).addClass('fun-sort-active');
        if(flag==0){
            flag=1;
            $(this).find("i").html('&#xe6d6;');
        }else{
            flag=0;
            $(this).find("i").html('&#xe6d5;');
        }
        $(this).data("flag",flag);  
    })

    // $(document).on('ajaxStart',
    //     function(){
    //         console.log('ajaxStart');
    //     }).on('ajaxStop',
    //     function(){
    //         console.log('ajaxStop');
    // })

    $("th.fun-sort2").append('<i class="Hui-iconfont zhuan90">&#xe6ee;</i>');//添加样式
    $(document).on('click','th.fun-sort2',function(){
        // console.log(kk)
        
        
        var sortname=$(this).data("name");
        var flag=$(this).data("flag");

        
        orderby='order='+sortname+'&desc='+flag;

        kk=API+'?'+search+'&'+orderby;

        // console.log("search:"+search)
        // console.log("orderby:"+orderby)

        loaddata(kk,1);
        $('th.fun-sort2').removeClass('fun-sort-active');
        $('th.fun-sort2').find('i').html('&#xe6ee;').addClass('zhuan90');
        $(this).find('i').removeClass('zhuan90');
        $(this).addClass('fun-sort-active');
        if(flag==0){
            flag=1;
            $(this).find("i").html('&#xe6d6;');
        }else{
            flag=0;
            $(this).find("i").html('&#xe6d5;');
        }
        $(this).data("flag",flag);  
    })

       


})








